package own.stu.jobgib.playown.io.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class AbstractNonblockingServer extends TServer {

    protected final Logger LOGGER = LoggerFactory.getLogger(getClass().getName());

    TServerSocket serverSocket;

    public void serve() {
        if (!startThreads()) {
            return;
        }

        if (!startListening()) {
            return;
        }

        setServing(true);

        // will block while we serve
        waitForShutdown();

        setServing(false);

        stopListening();
    }

    private void stopListening() {
        serverSocket.close();
    }

    private boolean startListening() {
        try {
            serverSocket.listen();
            return true;
        } catch (Exception ttx) {
            LOGGER.error("Failed to start listening on server socket!", ttx);
            return false;
        }
    }

    // start any threads required for serving
    protected abstract boolean startThreads();

    // block until threads handing the serving have been shut down
    protected abstract void waitForShutdown();


}
